package com.lancoo.answer.component

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.text.Html
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.view.animation.LinearInterpolator
import android.webkit.*
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.ivan.GlideEngine
import com.ivan.easyphotos.EasyPhotos
import com.lancoo.answer.R
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.Item
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.eventBean.KlgEvenBean
import com.lancoo.answer.util.DensityUtils
import com.lancoo.answer.util.DensityUtils.dp2px
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.WebStyleUtils
import com.lancoo.answer.widget.CustomScrollView
import com.lancoo.answer.widget.KWebView
import com.lancoo.answer.widget.PaletteView
import com.rxjava.rxlife.RxLife
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.roundToInt


/**
 * Created by Dadong on 2021/12/6
 * @Describe: 带交互带webview
 * 点击题干，回调position
 * 设置position，滚动到指定位置
 * 点击图片查看大图
 */

class InteractWebView : ConstraintLayout, PaletteView.Callback, View.OnClickListener {
    private lateinit var interactWebView: KWebView
    private var scale = 0f
    private var currentY = 0
    private var lastY = 0
    var isIndentation = false //是否缩紧
    private var isKlg = false
    private var quesIndex = ""
    private var subLeader = ""
    private var ques: Ques? = null

    //新增划线功能
    private var canPaletteView = false //开启画笔，默认关闭
    private lateinit var sv: CustomScrollView
    private lateinit var mLayoutTools: LinearLayout
    private lateinit var rl: RelativeLayout
    private lateinit var mUndoView: View
    private lateinit var mRedoView: View
    private lateinit var mPenView: View
    private lateinit var mPaletteView: PaletteView
    private lateinit var cl: ConstraintLayout
    private var isAnimDoing = false
    /*######################################*/


    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        initView(context)
    }

    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
        initView(context)
    }

    private fun initView(context: Context) {
        LayoutInflater.from(context).inflate(R.layout.ev_view_interact_webview, this, true)
        interactWebView = findViewById(R.id.web_view)
        sv = findViewById(R.id.sv)
        scale = resources.displayMetrics.density
        val view = rootView
        rl = view.findViewById(R.id.rl)
        cl = view.findViewById(R.id.cl)
        mPaletteView = view.findViewById<PaletteView>(R.id.palette)
        mUndoView = view.findViewById<View>(R.id.undo)
        mRedoView = view.findViewById<View>(R.id.redo)
        mPenView = view.findViewById<View>(R.id.pen)
        mLayoutTools = view.findViewById<LinearLayout>(R.id.LayoutTools)
        mPenView.setSelected(false)
        mPaletteView.setCallback(this)
        mPaletteView.setEnabled(false)
        mUndoView.setOnClickListener(this)
        mRedoView.setOnClickListener(this)
        mPenView.setOnClickListener(this)
        closePalette()
    }

    //防止后续定制需求，特接收ques
    fun setQues(ques: Ques?) {
        if (ques == null) {
            return
        }
        this.ques = ques
        if (!ques.QuesIndexText.isNullOrEmpty()) {
            quesIndex = ques.QuesIndexText!!
        }
        if (!ques.QuesSubLeader.isNullOrEmpty()) {
            subLeader = ques.QuesSubLeader!!
        }
    }

    fun setIsIndentation(isIndentation: Boolean) {
        this.isIndentation = isIndentation
    }

    //设置显示的数据
    fun initWebView(activity: Activity, url: String, callback: Callback? = null) {
        var body = ""
        if (!quesIndex.isNullOrEmpty()) {
            val textView = TextView(context)
            textView.text = Html.fromHtml(quesIndex).toString()
            var indexText = textView.text //这么写是为了去除标题的样式
            body = "<p align='center'><strong>$indexText</strong></p>"
        }
        if (!subLeader.isNullOrEmpty()) {
            val textView = TextView(context)
            textView.text = Html.fromHtml(subLeader).toString()
            var leaderText = textView.text //这么写是为了去除标题的样式
            body = "$body<p align='left'><i>$leaderText</i></p>"
        }
        body += url
        interactWebView.isVerticalScrollBarEnabled = false
        WebStyleUtils.showWebViewCssStyle(
            activity,
            interactWebView,
            body,
            isIndentation,
            isKlg
        )

        interactWebView.addJavascriptInterface(
            JSInterface(activity, callback), "Android"
        )
        interactWebView.webViewClient = object : WebViewClient() {
            @SuppressLint("ServiceCast")
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                callback?.finishCallback()
                WebStyleUtils.setWebImageClick(view, "Android")
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                //如果对不同的地址需要做不同的处理的话//if(url.contains("")){//}
                return true
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                handler.proceed()
            }
        }

        interactWebView.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
//                openPalette()
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                interactWebView.isVerticalScrollBarEnabled = true
                lastY = oldt
            }

        })

        sv.setOnScrollChangeListener(object : OnScrollChangeListener {
            override fun onScrollChange(
                v: View?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if (canPaletteView) {
                    mPaletteView.visibility = View.GONE
                    mUndoView.visibility = View.GONE
                    mRedoView.visibility = View.GONE
                    mPenView.visibility = View.GONE
                    mLayoutTools.visibility = View.GONE
                }
            }
        })
        sv.viewTreeObserver.addOnScrollChangedListener(object : OnScrollChangedListener {
            override fun onScrollChanged() {
                if (canPaletteView && !isAnimDoing) {
                    isAnimDoing = true
                    Single.timer(3000, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .`as`(RxLife.`as`(this@InteractWebView))
                        .subscribe({
                            mPaletteView.visibility = View.VISIBLE
                            mUndoView.visibility = View.VISIBLE
                            mRedoView.visibility = View.VISIBLE
                            mPenView.visibility = View.VISIBLE
                            mLayoutTools.visibility = View.VISIBLE
                            setAnimateYUp(mLayoutTools!!) // 显示工具弹窗
                            isAnimDoing = false
                        }) { throwable: Throwable? -> }
                }
            }
        })

        // 支持本地图片的加载
        val webSettings: WebSettings = interactWebView.settings
        setFontSize()
        webSettings.allowFileAccess = true
        webSettings.allowFileAccessFromFileURLs = true
        webSettings.allowUniversalAccessFromFileURLs = true
//        interactWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            interactWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        }
        interactWebView.settings.blockNetworkImage = false;
    }

    /**
     * 用于展示带交互的webView 是否高亮显示
     * @param isAnswer
     * true:作答中，字体蓝色 false:查看
     * （1）:正确答案 字体绿色
     * （2）:错误答案 字体红色
     * @param showItemAnswer
     * true 显示标准答案，false 屏蔽标准答案
     */
    fun loadUrl(
        item: Item,
        isSelect: Boolean = false,
        isAnswer: Boolean = true,
        showItemAnswer: Boolean = false
    ) {
        val itemSortIndex = item.ItemSortIndex
        val itemAnswer = item.ItemAnswer
        var stuAnswer = Gson().toJson(item.StuAnswer).replace("\"", "")
        if (isSelect) { //比如说填空题，获得焦点的一空背景变蓝
            interactWebView.loadUrl(
                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#ceebff" + "','" + "2px" + "','" + "1px solid #666666" + "')"
            )
        } else { //比如说填空题，未获得焦点的空背景透明
            interactWebView.loadUrl(
                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #666666" + "')"
            )
        }

        interactWebView.loadUrl( //【析】颜色变黄
            "javascript:setTextColor('" + "anlysis" + item.SortIndex +
                    "','" + "#ff9900" + "')"
        )


        if (isAnswer) {
            interactWebView.loadUrl(//获得焦点的作答内容变蓝
                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                        + "','" + "<font color=\"#0099ff\">"
                        + "&nbsp&nbsp&nbsp&nbsp&nbsp" + stuAnswer + "&nbsp&nbsp&nbsp&nbsp&nbsp" + "</font>')"
            )
        } else {
            if (stuAnswer.isEmpty()) {
                stuAnswer = "未填写"
            }

            if (ConstantBean.taskControlBean!!.expired) { //此处适配过期试卷
                if (showItemAnswer) {//展示标准答案
                    interactWebView.loadUrl(
                        "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                + "','" + "&nbsp&nbsp"
                                + "<font color=\"#0099ff\">" + stuAnswer + "</font>"
                                + "<font color=\"#00c063\">" + "(" + itemAnswer + ")" + "</font>"
                                + "&nbsp&nbsp" + " ')"
                    )
                } else {
                    interactWebView.loadUrl(
                        "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                + "','" + "&nbsp&nbsp"
                                + "<font color=\"#0099ff\">" + stuAnswer + "</font>"
                                + "&nbsp&nbsp" + " ')"
                    )
                }
                return
            }
            if (item.ScoreRate < 0.6f) { //是否及格
                if (showItemAnswer) {//展示标准答案
                    if (item.EvalScore < 0) {//未评语
                        interactWebView.loadUrl(
                            "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                    + "','" + "&nbsp&nbsp"
                                    + "<font color=\"#0099ff\">" + stuAnswer + "</font>"
                                    + "<font color=\"#00c063\">" + "(" + itemAnswer + ")" + "</font>"
                                    + "&nbsp&nbsp" + " ')"
                        )
                    } else {
                        interactWebView.loadUrl(
                            "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                    + "','" + "&nbsp&nbsp"
                                    + "<font color=\"#ff4c4c\">" + stuAnswer + "</font>"
                                    + "<font color=\"#00c063\">" + "(" + itemAnswer + ")" + "</font>"
                                    + "&nbsp&nbsp" + " ')"
                        )
                    }
                } else {
                    if (item.EvalScore < 0) { //未评阅
                        interactWebView.loadUrl(
                            "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                    + "','" + "&nbsp&nbsp"
                                    + "<font color=\"#0099ff\">" + stuAnswer + "</font>"
                                    + "&nbsp&nbsp" + " ')"
                        )
                    } else {
                        interactWebView.loadUrl(
                            "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                    + "','" + "&nbsp&nbsp"
                                    + "<font color=\"#ff4c4c\">" + stuAnswer + "</font>"
                                    + "&nbsp&nbsp" + " ')"
                        )
                    }
                }
            } else {
                interactWebView.loadUrl(
                    "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                            + "','" + "<font color=\"#00c063\">"
                            + "&nbsp&nbsp&nbsp&nbsp&nbsp" + stuAnswer + "&nbsp&nbsp&nbsp&nbsp&nbsp" + "</font>')"
                )
            }
        }
    }

    /**
     * 填空题 图片作答，查看
     */
    fun loadImageUrl(
        activity: Activity,
        item: Item
    ) {
        val imagePath = item.ScanImagePath
        val itemAnswer = item.ItemAnswer
        val itemSortIndex = item.ItemSortIndex
        val state = item.State
        Glide.with(activity).asBitmap().load(imagePath)
            .into(object : SimpleTarget<Bitmap?>() {
                override fun onResourceReady(
                    bitmap: Bitmap,
                    transition: Transition<in Bitmap?>?
                ) {
                    val screenWidth = DensityUtils.getScreenWidth(activity) / 5 * 2
                    val width: Int = if (bitmap.width > screenWidth) {
                        screenWidth
                    } else {
                        bitmap.width
                    }
                    if (item.ScoreRate < 0.6f) {
                        if (state == 0) {//未评阅
                            interactWebView.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','"
                                        + "<IMG hspace=2 src=" + imagePath + " style = \"border:2px solid#ff4c4c\" align=left|bottom width=" + width + "px>"
                                        + " ')"
                            )
                        } else {
                            interactWebView.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','"
                                        + "<IMG hspace=2 src=" + imagePath + " style = \"border:2px solid#ff4c4c\" align=left|bottom width=" + width + "px>"
                                        + " ')"
                            )
                        }
                    } else {
                        if (state == 0) {//未评阅
                            interactWebView.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','"
                                        + "<IMG hspace=2 src=" + imagePath + " style = \"border:2px solid#00c063\" align=left|bottom width=" + width + "px>"
                                        + " ')"
                            )
                        } else {
                            interactWebView.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','"
                                        + "<IMG hspace=2 src=" + imagePath + " style = \"border:2px solid#00c063\" align=left|bottom width=" + width + "px>"
                                        + " ')"
                            )
                        }

                    }
                }
            })
    }

    /**
     * 查看原题 (不带学生作答)
     * 用于展示带交互的webView 是否高亮显示
     * @param showItemAnswer
     * true 显示标准答案，false 屏蔽标准答案
     */
    fun loadOriginUrl(
        item: Item,
        isSelect: Boolean = false,
        showItemAnswer: Boolean = false
    ) {
        val itemSortIndex = item.ItemSortIndex
        val itemAnswer = item.ItemAnswer?.replace("$/", "或")?.replace("'", "’")
        if (isSelect) {
            interactWebView.loadUrl(
                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#ceebff" + "','" + "2px" + "','" + "1px solid #666666" + "')"
            )
        } else {
            interactWebView.loadUrl(
                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                        "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #666666" + "')"
            )
        }
        interactWebView.loadUrl(
            "javascript:setTextColor('" + "anlysis" + item.SortIndex +
                    "','" + "#ff9900" + "')"
        )
        if (showItemAnswer) {
            interactWebView.loadUrl(
                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                        + "','" + "&nbsp&nbsp"
                        + "<font color=\"#00c063\">" + itemAnswer + "</font>"
                        + "&nbsp&nbsp" + " ')"
            )
        } else {
            interactWebView.loadUrl(
                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                        + "','" + "&nbsp&nbsp"
                        + "&nbsp&nbsp" + " ')"
            )
        }
    }


    //翻译题高亮
    fun loadTranslateUrl(itemSortIndex: String = "", isSelect: Boolean = false) {
        if (ques?.specialAnswerMethod == 1) {
            return
        }
        if (isSelect) {
            interactWebView.loadUrl(
                "javascript:setTextColor('$itemSortIndex','#0099ff')"
            )
        } else {
            interactWebView.loadUrl(
                "javascript:setTextColor('$itemSortIndex','#666666')"
            )
        }
    }

    //显示不确定标记
    fun showFlag(itemSortIndex: String = "", visible: Int) { // 0 不可见，1 可见
        interactWebView.loadUrl(
            "javascript:showFlagWithId('$itemSortIndex', '$visible', '\"file:///android_asset/images/mark.png\"')"
        )
    }

    /**
     *  解析是否可见
     *  @param visible 1:可见; 0:不可见;
     */
    fun showOrHideAnalysisButton(visible: Int) {
        interactWebView.loadUrl(
            "javascript:showOrHideAnalysisButton('$visible')"
        )
    }

    /**
     * 篇章翻译序号是否可见
     * @param visible 1:可见; 0:不可见;
     */
    fun showOrHideClauseIndex(visible: Int) {
        val invisible = 0
        if (ques?.specialAnswerMethod == 1) {
            interactWebView.loadUrl(
                "javascript:showOrHideClauseIndex('$invisible')"
            )
            return
        }
        interactWebView.loadUrl(
            "javascript:showOrHideClauseIndex('$visible')"
        )
    }

    //JS点击事件处理 回调webView中被点击的位置
    inner class JSInterface(var activity: Activity, var callback: Callback?) {
        @JavascriptInterface
        fun clickFunction(position: String) {
            activity.runOnUiThread {
                callback?.clickCallback(position)
            }
        }

        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val imgList = ArrayList<String>()
            imgList.add(img)
            EasyPhotos.startPreviewPaths(
                context as FragmentActivity, GlideEngine.getInstance(),
                imgList, true, 0
            )
        }

        @JavascriptInterface
        fun clickKlg(content: String, code: String) {
            Log.e("clickKlg", "点击知识点：" + content)
            Log.e("clickKlg", "点击知识点：" + code)
            val bean = KlgEvenBean()
            bean.setKlgCode(code)
            bean.setKlgName(content)
            bean.setIndex(-1)
            EventBus.getDefault().post(bean)
        }
    }

    //翻译题设置需要滚动到的位置
    fun scrollTranslatePosition(position: String) {
        if (ques?.specialAnswerMethod == 1) {
            return
        }
        val height = interactWebView.height
        interactWebView.evaluateJavascript(
            "javascript:topHeight('$position')",
            ValueCallback<String?> { value ->
                var dp = 0
                dp = if (value == "null") {
                    0
                } else {
                    Integer.valueOf(value!!)
                }
                currentY = ((dp * scale).roundToInt() - dp2px(
                    context,
                    height / 10f
                )).toInt()//此处关键，保持被点击的区域处于可见区域中间位置
                val anim: ObjectAnimator =
                    ObjectAnimator.ofInt(
                        interactWebView, "scrollY", lastY, currentY
                    )
                anim.setDuration(500).start()
                lastY = currentY
            })
    }

    //设置需要滚动到的位置
    fun scrollPosition(position: String) {
        val sp = context.getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE)
        val fontSizeIndex = sp.getInt(AnswerConstant.SP_FONT_SIZE, 1)
        val fontSize = (100 + (fontSizeIndex - 1) * 20) / 100.0f
        val height = interactWebView.height
        var dp = 0
        interactWebView.evaluateJavascript(
            "javascript:topHeight('blank$position')",
            ValueCallback<String?> { value ->
                dp = if (value == "null") {
                    0
                } else {
                    Integer.valueOf(value!!)
                }
                currentY = ((dp * scale).roundToInt() - dp2px(
                    context,
                    height / 16f
                )).toInt()//此处关键，保持被点击的区域处于可见区域中间位置
                val anim: ObjectAnimator =
                    ObjectAnimator.ofInt(
                        sv, "scrollY", currentY, lastY
                    )
                Log.d("shishisaonian", "$currentY   $lastY")
                anim.setDuration(500).start()
                lastY = currentY
            })

        //不知道什么原因，执行第二遍定位就没问题了
        interactWebView.evaluateJavascript(
            "javascript:topHeight('blank$position')",
            ValueCallback<String?> { value ->
                dp = if (value == "null") {
                    0
                } else {
                    Integer.valueOf(value!!)
                }
                currentY = ((dp * scale).roundToInt() - dp2px(
                    context,
                    height / 16f
                )).toInt()//此处关键，保持被点击的区域处于可见区域中间位置
                val anim: ObjectAnimator =
                    ObjectAnimator.ofInt(
                        sv, "scrollY", currentY, lastY
                    )
                Log.d("shishisaonian", "$currentY   $lastY")
                anim.setDuration(500).start()
                lastY = currentY
            })
    }

    //todo 设置交互显示的内容
    fun setContent(
        itemSortIndex: String,
        imagePath: String,
        stuAnswer: String,
        itemAnswer: String,
    ) {
        var stuAnswerX = stuAnswer
        if (stuAnswer.isEmpty() && imagePath.isEmpty()) {
            stuAnswerX = "未填写"
        }
        interactWebView.loadUrl(
            "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                    + "','" + "&nbsp&nbsp"
                    + "<font color=\"#ff0000\">" + stuAnswerX + "</font>"
                    + "<font color=\"#00b30d\">" + "(" + itemAnswer + ")" + "</font>"
                    + "&nbsp&nbsp" + " ')"
        )
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        return super.dispatchTouchEvent(ev)
    }

    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%划线标注%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    override fun onUndoRedoStatusChanged() {}

    override fun onChangePenState() {
        mPenView!!.performClick()
    }

    override fun onClick(v: View) {

        val id = v.id
        if (id == R.id.undo) {
            mPaletteView!!.undo()
        } else if (id == R.id.redo) {
            mPaletteView!!.redo()
        } else if (id == R.id.pen) {
            if (v.isSelected) {
                interactWebView.findViewById<View>(R.id.web_view).isNestedScrollingEnabled =
                    true
                v.isSelected = false
                mPaletteView!!.isEnabled = false //关闭画笔功能
                //todo 此处添加开启viewpager2左右滑动的消息通知
                setAnimateYUp(mLayoutTools!!) //todo 显示工具弹窗
            } else {
                interactWebView.findViewById<View>(R.id.web_view).isNestedScrollingEnabled =
                    false
                v.isSelected = true
                mPaletteView!!.isEnabled = true //开启画笔功能
                mPaletteView!!.mode = PaletteView.Mode.DRAW
                mPaletteView!!.resetPen()
                //todo 此处添加禁止viewpager2左右滑动的消息通知
                setAnimateYDown(mLayoutTools!!) //todo 隐藏工具弹窗
            }
        }
    }

    public fun openPalette() {
        if (ConstantBean.taskControlBean != null) {
            if (ConstantBean.taskControlBean!!.isForceCloseDash) {
                closePalette()
                return
            }
        }
        canPaletteView = true
        mPaletteView.visibility = View.VISIBLE
        mUndoView.visibility = View.VISIBLE
        mRedoView.visibility = View.VISIBLE
        mPenView.visibility = View.VISIBLE
        mLayoutTools.visibility = View.VISIBLE
        setAnimateYUp(mLayoutTools!!) // 显示工具弹窗
        val linearParams: RelativeLayout.LayoutParams =
            mPaletteView.layoutParams as RelativeLayout.LayoutParams //取控件textView当前的布局参数
        linearParams.height = max(
            DensityUtils.dp2px(context, interactWebView.contentHeight.toFloat()),
            DensityUtils.dp2px(context, 350f)
        ) + DensityUtils.dp2px(context, 56f)
        mPaletteView.layoutParams = linearParams //使设置好的布局参数应用到控件

    }

    public fun closePalette() {
        canPaletteView = false
        mPaletteView.visibility = View.GONE
        mUndoView.visibility = View.GONE
        mRedoView.visibility = View.GONE
        mPenView.visibility = View.GONE
        mLayoutTools.visibility = View.GONE
    }

    private fun setAnimateYDown(view: View) {
        val objectAnimator = ObjectAnimator.ofFloat(view, "translationY", 0f, 180f)
        objectAnimator.duration = 300 //设置移动时间
        objectAnimator.repeatCount = 0
        objectAnimator.interpolator = LinearInterpolator()
        objectAnimator.start() //开始动画
    }

    private fun setAnimateYUp(view: View) {
        val objectAnimator = ObjectAnimator.ofFloat(view, "translationY", 180f, 0f)
        objectAnimator.duration = 300 //设置移动时间
        objectAnimator.repeatCount = 0
        objectAnimator.interpolator = LinearInterpolator()
        objectAnimator.start() //开始动画
    }
    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
    /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/


    fun release() {
        if (interactWebView != null) {
            interactWebView.stopLoading()
            interactWebView.clearHistory()
            interactWebView.removeAllViews()
            interactWebView.destroy()
        }
    }

    fun setDisableInterceptTouch(b: Boolean) {
        if (interactWebView != null) {
            interactWebView.setDisableInterceptTouch(b)
        }
    }

    fun setScrollBarEnabled(enable: Boolean) {
        interactWebView.isVerticalScrollBarEnabled = enable
    }

    interface Callback {
        fun clickCallback(position: String)
        fun finishCallback()
    }

    fun loadHighKLg(klg: String) {
        interactWebView.loadUrl(klg)
    }

    fun setKlg(isKlg: Boolean) {
        this.isKlg = isKlg
    }

    fun setFontSize() {
        ExamFontSizeAdjustUtils.adjustWebViewFontSize(interactWebView)
    }
}